/* Filename: ./5-client.c
 * Description:
 * Last modified: humble 2020-11-12 10:31:31
 * $ gcc -Wall 5-client.c -o 5-client -levent
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

#define PORT (2500)
#define BUFFER_SIZE (1024)

static void delay(int ms) { clock_t start = clock(); while(clock() - start < ms); }

static void read_cb(struct bufferevent *bev, void *user_data)
{
    char msg[BUFFER_SIZE] = {'\0'};
    struct evbuffer *input = bufferevent_get_input(bev);
    size_t sz = evbuffer_get_length(input);
    if (sz > 0) {
        bufferevent_read(bev, msg, sz);
        printf("%s\n", msg);
    }
}

static void write_cb(struct bufferevent *bev, void *user_data)
{
    //struct evbuffer *output = bufferevent_get_output(bev);
    //if (evbuffer_get_length(output) == 0) {
    //    printf("Output evbuffer is flushed\n");
    //    bufferevent_free(bev);
    //}
    //delay 1 second
    delay(1000);
    static int msg_num = 1;
    char reply_msg[1000] = {'\0'};
    char *str = "I am a message from client";
    memcpy(reply_msg, str, strlen(str));
    sprintf(reply_msg + strlen(str),"%d", msg_num);
    bufferevent_write(bev, reply_msg, strlen(reply_msg));
    msg_num++;
}

static void event_cb(struct bufferevent *bev, short events, void *user_data)
{
    if (events & BEV_EVENT_EOF) {
        printf("Connection closed\n");
    }
    else if (events & BEV_EVENT_ERROR) {
        printf("Got an error on the connection: %s\n", strerror(errno));
    }
    else if( events & BEV_EVENT_CONNECTED) {
        printf("Connect succeed\n");
        //客户端链接成功后，给服务器发送第一条消息
        char *reply_msg = "I am a message from client";
        bufferevent_write(bev, reply_msg, strlen(reply_msg));
        return ;
    }

    bufferevent_free(bev);
}

int main()
{
    printf("I am client\n");
#ifdef WIN32
    WSAData wsaData;
    WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
    struct sockaddr_in srv;
    memset(&srv, 0, sizeof(srv));
    srv.sin_family = AF_INET;
    srv.sin_port = htons(PORT);
    inet_pton(AF_INET, "127.0.0.1", &srv.sin_addr.s_addr);

    struct event_base *base = event_base_new();
    if (!base) { printf("Could not initialize libevent\n"); return 1; }

    struct bufferevent* bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);
    int flag=bufferevent_socket_connect(bev, (struct sockaddr *)&srv,sizeof(srv));
    bufferevent_enable(bev, EV_READ | EV_WRITE);
    if(-1==flag) { printf("Connect failed\n"); return 1; }

    event_base_dispatch(base);
    event_base_free(base);

    printf("done\n");
    return 0;
}
